package io.chenglicun.modules.oss.cloud;

import com.obs.services.ObsClient;
import io.chenglicun.common.exception.ErrorCode;
import io.chenglicun.common.exception.RenException;

import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;

/**
 * 华为云存储
 *
 * @author HB
 */
public class HuaweiCloudStorageService extends AbstractCloudStorageService {

    public HuaweiCloudStorageService(CloudStorageConfig config) {
        this.config = config;
    }

    public ObsClient createTransferManager() {
        ObsClient client = new ObsClient(config.getHuaweiyunAccessKey(), config.getHuaweiyunSecretAccessKey(),
                config.getHuaweiyunEndPoint());
        return client;
    }

    public void shutdownTransferManager(ObsClient obsClient) {
        try {
            obsClient.close();
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    @Override
    public String upload(byte[] data, String path) {
        return upload(new ByteArrayInputStream(data), path);
    }

    @Override
    public String upload(InputStream inputStream, String path) {
        ObsClient client = createTransferManager();

        try {
            client.putObject(config.getHuaweiyunBucketName(), path, inputStream);
            shutdownTransferManager(client);
        } catch (Exception e) {
            throw new RenException(ErrorCode.OSS_UPLOAD_FILE_ERROR, e, "");
        }

        return config.getHuaweiyunDomain() + "/" + path;
    }

    @Override
    public String uploadSuffix(byte[] data, String suffix) {
        return upload(data, getPath(config.getHuaweiyunPrefix(), suffix));
    }

    @Override
    public String uploadSuffix(InputStream inputStream, String suffix) {
        return upload(inputStream, getPath(config.getHuaweiyunPrefix(), suffix));
    }

    @Override
    public void deleteFile(String path) {
        ObsClient client = new ObsClient(config.getHuaweiyunAccessKey(),
                config.getHuaweiyunSecretAccessKey(),config.getHuaweiyunEndPoint());
        try {
            client.deleteObject(config.getHuaweiyunBucketName(), path);
            client.close();
        } catch (Exception e){
            throw new RenException(ErrorCode.OSS_UPLOAD_FILE_ERROR, e, "");
        }
    }
}